#include						"QtAsyncTcpSocket.h"

QtAsyncTcpSocket::QtAsyncTcpSocket() : ASocket(1)
{
	_buffer.init();
	_type = ASocket::TCP;
}

QtAsyncTcpSocket::~QtAsyncTcpSocket()
{
	_socket.deleteLater();
}

void							QtAsyncTcpSocket::init()
{
	connect(&_socket, SIGNAL(readyRead()), this, SLOT(handleRead()));
	connect(&_socket, SIGNAL(connected()), this, SLOT(handleConnect()));
	connect(&_socket, SIGNAL(disconnected()), this, SLOT(handleDisconnect()));
}
	
void							QtAsyncTcpSocket::connectToHost(const std::string &ip, const std::string &port)
{
	_socket.connectToHost(QString(ip.c_str()), QString(port.c_str()).toShort());
}

void							QtAsyncTcpSocket::sendPacket(Packet *packet)
{
	size_t						size = packet->size();

	_socket.write((const char *)packet->toTcpNetworkPacket(), size + sizeof(unsigned short));
}

void							QtAsyncTcpSocket::_receiveTcp(size_t bytes_transferred)
{
	for (size_t cnt = 0 ; cnt < bytes_transferred; ++cnt)
		_buffer.write(_tmp_buf[cnt]);
	if (!_current_msg && _buffer.size() >= 2)
		_getOrderSize();
	while (_buffer.size() > 0 && _buffer.size() >= _current_msg)
	{
		std::vector<byte>		*receipt = new std::vector<byte>;
		for (unsigned short cnt = 0; cnt < _current_msg; ++cnt)
			receipt->push_back(_buffer.read());
		_handler->harvest(this, receipt);
		_current_msg = 0;
		if (_buffer.size() >= 2)
			_getOrderSize();
	}	
}

void							QtAsyncTcpSocket::handleRead()
{
	size_t						received = 0;

	received = _socket.read((char*)_tmp_buf, 4096);
	_receiveTcp(received);
}

void							QtAsyncTcpSocket::close()
{
	_socket.close();
}

QHostAddress					QtAsyncTcpSocket::getIp() const
{
	return _ip;
}

void 							QtAsyncTcpSocket::handleConnect()
{
	_ip = _socket.peerAddress();
	emit connected(_ip);
}

void							QtAsyncTcpSocket::handleDisconnect()
{
	emit disconnected(_ip);
}
